package com.example.demo.service.wx.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.constant.RedisHashConst;
import com.example.demo.service.wx.IWxService;
import com.example.demo.util.CommWxUrl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

/**
 * @Description:
 * @author: liyuan
 * @data 2020-11-23 09:58
 */
@Service
public class WxServiceImpl implements IWxService {
    @Value("${miniProgram.appId}")
    private String APPID;
    @Value("${miniProgram.appSecret}")
    private String SECRET;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RestTemplate restTemplate;

    public String getToken() {
        String token = (String) stringRedisTemplate.opsForHash().get(RedisHashConst.HASHKEY, RedisHashConst.TOKEN);
        if (StringUtils.isEmpty(token)) {
            JSONObject tokenJSON = restTemplate.getForObject(CommWxUrl.getTokenUrl(APPID, SECRET), JSONObject.class);
            if (tokenJSON == null || tokenJSON.getString("access_token") == null) {
                return "";
            }
            token = tokenJSON.getString("access_token");
            stringRedisTemplate.opsForHash().put(RedisHashConst.HASHKEY, RedisHashConst.TOKEN, token);
        }
        return token;
    }

    public String getTicket() {
        String ticket = (String) stringRedisTemplate.opsForHash().get(RedisHashConst.HASHKEY, RedisHashConst.TICKET);
        if (ticket == null) {
            String token = getToken();
            if (StringUtils.isEmpty(token)) {
                return "";
            }
            String ticketUrl = CommWxUrl.genTicketUrl(token);
            JSONObject ticketData = restTemplate.getForObject(ticketUrl, JSONObject.class);
            if (ticketData == null || ticketData.getString("ticket") == null) {
                return "";
            }
            ticket = ticketData.getString("ticket");
            stringRedisTemplate.opsForHash().put(RedisHashConst.HASHKEY, RedisHashConst.TICKET, ticket);
        }
        return ticket;
    }
}
